<template>
  <px-form class="custom-form-ui equip-form" label-position="right" label-width="120px" @submit.prevent>
    <px-row :gutter="16">
      <px-col :span="6">
        <px-form-item label="点位名称">
          <px-input
            v-model="form.point"
            placeholder="请输入点位名称"
            maxlength="100"
            clearable
            @blur="form.point = $event.target.value.trim()"
            @keyup.enter="handleSearch"
          >
            <template #suffix>
              <px-icon class="pointer" @click="handleSearch"><Search /></px-icon>
            </template>
          </px-input>
        </px-form-item>
      </px-col>
      <px-col :span="6">
        <px-form-item label="科室">
          <px-select v-model="form.className" placeholder="请选择科室" filterable @change="classChanged">
            <px-option v-for="item in classNameList" :key="item.code" :label="item.name" :value="item.code" />
          </px-select>
        </px-form-item>
      </px-col>
      <px-col :span="6">
        <px-form-item label="系统">
          <px-tree-select
            v-model="form.systemCode"
            clearable
            filterable
            :props="defaultProps"
            :data="filterSystemList"
            check-strictly
            node-key="code"
            placeholder="请选择设备系统（树状图）"
            @node-click="handleNodeClick"
          />
        </px-form-item>
      </px-col>
      <px-col :span="6">
        <px-form-item label="报警级别">
          <px-select v-model="form.alarmLevel" placeholder="请选择报警级别" clearable>
            <px-option v-for="item in alarmLevelList" :key="item.key" :label="item.label" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-col>
      <px-col :span="6">
        <px-form-item label="报警类型">
          <px-select v-model="form.alarmType" placeholder="请选择报警类型" clearable>
            <px-option v-for="item in alarmTypeList" :key="item.value" :label="item.name" :value="item.value" />
          </px-select>
        </px-form-item>
      </px-col>
      <px-col :span="6">
        <px-form-item label="是否纳入报警统计分析" prop="countPointFlag">
          <px-select v-model="form.countPointFlag" style="width: 100%" placeholder="请选择是否纳入报警统计分析">
            <px-option key="1" label="是" value="Y" />
            <px-option key="2" label="否" value="N" />
          </px-select>
        </px-form-item>
      </px-col>
      <px-col :span="6">
        <px-button type="primary" @click="handleSearch">查询</px-button>
        <px-button @click="handleReset">重置</px-button>
      </px-col>
    </px-row>
  </px-form>
</template>

<script lang="ts" setup>
import { useRoute } from "vue-router";
import { computed, nextTick, onMounted, ref, watchEffect } from "vue";

import { queryDictData, querySystemTree } from "@/api/common";
import { querySystemSelect } from "@/api/equip/archive";

import type { FormType, OptionsType, QueryParams } from "../type";

const defaultProps = {
  children: "children",
  label: "name",
  value: "code"
};

const classNameList = JSON.parse(localStorage.getItem("classList"));

const route = useRoute();

const emits = defineEmits<{
  (e: "search", params: QueryParams): void;
}>();

const form = ref<FormType>({
  point: "",
  className: "",
  systemCode: "",
  alarmLevel: "",
  alarmType: "",
  countPointFlag: ""
});

const alarmTypeList = ref([]);
const alarmLevelList = ref<OptionsType>([]);
const systemIdList = ref<string[]>([]);
const allSystemList = ref<any[]>([]);
const systemListForCondition = ref<any[]>([]);

const queryParams = computed<QueryParams>(() => {
  return {
    point: form.value.point,
    className: form.value.className,
    alarmLevel: form.value.alarmLevel,
    alarmType: form.value.alarmType,
    countPointFlag: form.value.countPointFlag,
    systemIdList: systemIdList.value
  };
});

const filterSystemList = computed<any[]>(() => {
  if (allSystemList.value?.length > 0) return allSystemList.value;
  return systemListForCondition.value;
});

if (classNameList.length === 1) {
  form.value.className = classNameList[0].code;
}

const getAllSystemTree = async () => {
  try {
    const res = await querySystemSelect({ className: form.value.className });
    if ((res as any[]).length) {
      allSystemList.value = res as any[];
      systemListForCondition.value = [];
    }
  } catch (err) {
    console.log("queryAllSystemTree error", err);
  }
};

const getSystemTreeByCondition = async () => {
  try {
    const res = await querySystemTree({ className: form.value.className });
    if ((res as any[]).length) {
      systemListForCondition.value = res as any[];
      allSystemList.value = [];
    }
  } catch (err) {
    console.log("querySystemTree error", err);
  }
};

const getAlarmLevelList = async () => {
  const res = await queryDictData({ typeCode: "ALARM_LEVEL" });
  if (res?.length) {
    alarmLevelList.value = res.map(item => {
      return {
        label: item.name,
        value: item.value,
        key: item.id
      };
    });
  }
};

const getAlarmTypeList = async () => {
  if (form.value.className) {
    alarmTypeList.value = await queryDictData({ typeCode: `${form.value.className}_ALARM_TYPE` });
  } else {
    classNameList?.forEach(async item => {
      const res = await queryDictData({ typeCode: `${item.code}_ALARM_TYPE` });
      if (res) {
        alarmTypeList.value = alarmTypeList.value.concat(res);
      }
      alarmTypeList.value = alarmTypeList.value?.filter((obj, index, self) => {
        return self.map(x => x.value).indexOf(obj.value) === index;
      });
    });
  }
};

const classChanged = () => {
  if (form.value.systemCode) {
    form.value.systemCode = "";
  }
  form.value.alarmType = "";
  getAlarmTypeList();
};

const isAllSystemTreeItemType = (node: any) => {
  return "type" in node;
};

const getCodes = (node): string[] => {
  const codes = [node.code];
  if (node?.children?.length) {
    node.children.forEach(item => {
      codes.push(...getCodes(item));
    });
  }
  return codes;
};

const getNodeForSecondLevel = node => {
  let parentNode = node.parent;
  let parentNodeType = parentNode.data.type;

  while (parentNode && parentNodeType && parentNodeType !== "className") {
    parentNode = parentNode?.parent;
    parentNodeType = parentNode?.data?.type;
  }

  return parentNode;
};

// 点击左侧树节点，获取工厂、科室、系统、系统codes
const handleNodeClick = async (node, nodeData) => {
  if (isAllSystemTreeItemType(node)) {
    if (node.type === "className") {
      // 二级科室
      form.value.className = node.code;
      await nextTick();
      form.value.systemCode = "";
    } else if (node.type === "systemCategory") {
      // 三级及三级以下节点
      systemIdList.value = getCodes(node);
      const nodeForSecondLevel = getNodeForSecondLevel(nodeData);
      form.value.className = nodeForSecondLevel.data.code;
    }
  } else {
    systemIdList.value = getCodes(node);
  }
};

const handleSearch = () => {
  emits("search", queryParams.value);
};

if (route.query.point) {
  form.value.point = route.query.point as string;
  handleSearch();
}

defineExpose({
  search: handleSearch
});

const handleReset = () => {
  form.value = {
    point: "",
    className: "",
    systemCode: "",
    alarmLevel: "",
    alarmType: "",
    countPointFlag: ""
  };
  systemIdList.value = [];
  handleSearch();
};

watchEffect(() => {
  if (form.value.className) {
    getSystemTreeByCondition();
    return;
  }
  getAllSystemTree();
});

const init = () => {
  getAlarmLevelList();
  getAlarmTypeList();
};

init();
</script>
